Introduction to Open Data Science 2018 is a Massive Online Open Course(Mooc) which teaches the basics of data science, tools needed (like GitHub and RStudio) and languages like R. Course teaches about the amount, importance and possibilities of data. Course highlights open data and open source free software. This is a link to my GitHub repository: https://github.com/practising123/IODS-project
library(dplyr)
library(ggplot2)
library(GGally)
lrn14 <- read.table("http://www.helsinki.fi/~kvehkala/JYTmooc/JYTOPKYS3-
data.txt", sep="\t", header=TRUE)
dim(lrn14)
## [1] 183 60
str(lrn14)
## 'data.frame': 183 obs. of 60 variables:
## $ Aa : int 3 2 4 4 3 4 4 3 2 3 ...
## $ Ab : int 1 2 1 2 2 2 1 1 1 2 ...
## $ Ac : int 2 2 1 3 2 1 2 2 2 1 ...
## $ Ad : int 1 2 1 2 1 1 2 1 1 1 ...
## $ Ae : int 1 1 1 1 2 1 1 1 1 1 ...
## $ Af : int 1 1 1 1 1 1 1 1 1 2 ...
## $ ST01 : int 4 4 3 3 4 4 5 4 4 4 ...
## $ SU02 : int 2 2 1 3 2 3 2 2 1 2 ...
## $ D03 : int 4 4 4 4 5 5 4 4 5 4 ...
## $ ST04 : int 4 4 4 4 3 4 2 5 5 4 ...
## $ SU05 : int 2 4 2 3 4 3 2 4 2 4 ...
## $ D06 : int 4 2 3 4 4 5 3 3 4 4 ...
## $ D07 : int 4 3 4 4 4 5 4 4 5 4 ...
## $ SU08 : int 3 4 1 2 3 4 4 2 4 2 ...
## $ ST09 : int 3 4 3 3 4 4 2 4 4 4 ...
## $ SU10 : int 2 1 1 1 2 1 1 2 1 2 ...
## $ D11 : int 3 4 4 3 4 5 5 3 4 4 ...
## $ ST12 : int 3 1 4 3 2 3 2 4 4 4 ...
## $ SU13 : int 3 3 2 2 3 1 1 2 1 2 ...
## $ D14 : int 4 2 4 4 4 5 5 4 4 4 ...
## $ D15 : int 3 3 2 3 3 4 2 2 3 4 ...
## $ SU16 : int 2 4 3 2 3 2 3 3 4 4 ...
## $ ST17 : int 3 4 3 3 4 3 4 3 4 4 ...
## $ SU18 : int 2 2 1 1 1 2 1 2 1 2 ...
## $ D19 : int 4 3 4 3 4 4 4 4 5 4 ...
## $ ST20 : int 2 1 3 3 3 3 1 4 4 2 ...
## $ SU21 : int 3 2 2 3 2 4 1 3 2 4 ...
## $ D22 : int 3 2 4 3 3 5 4 2 4 4 ...
## $ D23 : int 2 3 3 3 3 4 3 2 4 4 ...
## $ SU24 : int 2 4 3 2 4 2 2 4 2 4 ...
## $ ST25 : int 4 2 4 3 4 4 1 4 4 4 ...
## $ SU26 : int 4 4 4 2 3 2 1 4 4 4 ...
## $ D27 : int 4 2 3 3 3 5 4 4 5 4 ...
## $ ST28 : int 4 2 5 3 5 4 1 4 5 2 ...
## $ SU29 : int 3 3 2 3 3 2 1 2 1 2 ...
## $ D30 : int 4 3 4 4 3 5 4 3 4 4 ...
## $ D31 : int 4 4 3 4 4 5 4 4 5 4 ...
## $ SU32 : int 3 5 5 3 4 3 4 4 3 4 ...
## $ Ca : int 2 4 3 3 2 3 4 2 3 2 ...
## $ Cb : int 4 4 5 4 4 5 5 4 5 4 ...
## $ Cc : int 3 4 4 4 4 4 4 4 4 4 ...
## $ Cd : int 4 5 4 4 3 4 4 5 5 5 ...
## $ Ce : int 3 5 3 3 3 3 4 3 3 4 ...
## $ Cf : int 2 3 4 4 3 4 5 3 3 4 ...
## $ Cg : int 3 2 4 4 4 5 5 3 5 4 ...
## $ Ch : int 4 4 2 3 4 4 3 3 5 4 ...
## $ Da : int 3 4 1 2 3 3 2 2 4 1 ...
## $ Db : int 4 3 4 4 4 5 4 4 2 4 ...
## $ Dc : int 4 3 4 5 4 4 4 4 4 4 ...
## $ Dd : int 5 4 1 2 4 4 5 3 5 2 ...
## $ De : int 4 3 4 5 4 4 5 4 4 2 ...
## $ Df : int 2 2 1 1 2 3 1 1 4 1 ...
## $ Dg : int 4 3 3 5 5 4 4 4 5 1 ...
## $ Dh : int 3 3 1 4 5 3 4 1 4 1 ...
## $ Di : int 4 2 1 2 3 3 2 1 4 1 ...
## $ Dj : int 4 4 5 5 3 5 4 5 2 4 ...
## $ Age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ Attitude: int 37 31 25 35 37 38 35 29 38 21 ...
## $ Points : int 25 12 24 10 22 21 21 31 24 26 ...
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
deep_questions <- c("D03", "D11", "D19", "D27", "D07", "D14", "D22", "D30","D06", "D15", "D23", "D31")
deep_columns <- select(lrn14, one_of(deep_questions))
deep <- rowMeans((deep_columns))
surface_questions <- c("SU02","SU10","SU18","SU26", "SU05","SU13","SU21","SU29","SU08","SU16","SU24","SU32")
surface_columns <- select(lrn14, one_of(surface_questions))
surf <- rowMeans(surface_columns)
strategic_questions <- c("ST01","ST09","ST17","ST25","ST04","ST12","ST20","ST28")
strategic_columns <- select(lrn14, one_of(strategic_questions))
stra <- rowMeans(strategic_columns)
keep_columns <- c("gender","Age","Attitude", "Points")
learning2014 <- select(lrn14, one_of(keep_columns))
learning2014$deep <- deep
learning2014$stra <- stra
learning2014$surf <- surf
learning2014 <-filter(learning2014, Points>0)
str(learning2014)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ Age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ Attitude: int 37 31 25 35 37 38 35 29 38 21 ...
## $ Points : int 25 12 24 10 22 21 21 31 24 26 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
dim(learning2014)
## [1] 166 7
write.table(learning2014, file = "data/learning2014.txt", row.names = TRUE)
new_table <- read.table(file = "data/learning2014.txt", header=TRUE)
dim(new_table)
## [1] 166 7
str(new_table)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ Age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ Attitude: int 37 31 25 35 37 38 35 29 38 21 ...
## $ Points : int 25 12 24 10 22 21 21 31 24 26 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
2.1
new_table <- read.table(file = "data/learning2014.txt", header=TRUE)
summary(new_table)
## gender Age Attitude Points deep
## F:110 Min. :17.00 Min. :14.00 Min. : 7.00 Min. :1.583
## M: 56 1st Qu.:21.00 1st Qu.:26.00 1st Qu.:19.00 1st Qu.:3.333
## Median :22.00 Median :32.00 Median :23.00 Median :3.667
## Mean :25.51 Mean :31.43 Mean :22.72 Mean :3.680
## 3rd Qu.:27.00 3rd Qu.:37.00 3rd Qu.:27.75 3rd Qu.:4.083
## Max. :55.00 Max. :50.00 Max. :33.00 Max. :4.917
## stra surf
## Min. :1.250 Min. :1.583
## 1st Qu.:2.625 1st Qu.:2.417
## Median :3.188 Median :2.833
## Mean :3.121 Mean :2.787
## 3rd Qu.:3.625 3rd Qu.:3.167
## Max. :5.000 Max. :4.333
2.2
p <- ggpairs(new_table, mapping = aes(col=gender, alpha=0.3), lower = list(combo = wrap("facethist", bins = 20)))
p
- Creates the plot of new_table and prints it.
table(cut(new_table$Age, breaks = seq(15,55,by=10)))
##
## (15,25] (25,35] (35,45] (45,55]
## 116 32 11 7
table(new_table$gender, cut(new_table$Attitude, breaks = seq(1,56,by=5)))
##
## (1,6] (6,11] (11,16] (16,21] (21,26] (26,31] (31,36] (36,41] (41,46]
## F 0 0 2 15 23 22 26 17 3
## M 0 0 0 3 2 11 17 17 4
##
## (46,51] (51,56]
## F 2 0
## M 2 0
2.3
my_model <- lm(Points ~ Attitude + stra + surf, data = new_table)
summary(my_model)
##
## Call:
## lm(formula = Points ~ Attitude + stra + surf, data = new_table)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.1550 -3.4346 0.5156 3.6401 10.8952
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.01711 3.68375 2.991 0.00322 **
## Attitude 0.33952 0.05741 5.913 1.93e-08 ***
## stra 0.85313 0.54159 1.575 0.11716
## surf -0.58607 0.80138 -0.731 0.46563
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared: 0.2074, Adjusted R-squared: 0.1927
## F-statistic: 14.13 on 3 and 162 DF, p-value: 3.156e-08
my_model <- lm(Points ~ Attitude, data = new_table)
2.4
summary(my_model)
##
## Call:
## lm(formula = Points ~ Attitude, data = new_table)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.63715 1.83035 6.358 1.95e-09 ***
## Attitude 0.35255 0.05674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
my_model <- lm(Points ~ Attitude, data = new_table)
summary(my_model)
##
## Call:
## lm(formula = Points ~ Attitude, data = new_table)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.63715 1.83035 6.358 1.95e-09 ***
## Attitude 0.35255 0.05674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
2.5 - Assumptions of linear regression models:
The errors are normally distributed
The errors are not correlated
The errors have constant variance
The size of a given error does not depend on the explanatory variables
plot(my_model, which =c(1))
- Residual vs fitted. Tells if there are patterns, patterns mean problem with the assumption. If there would be bigger residual on bigger values, the assumption(my_model) would need to be corrected. Residuals seem to be scattered evenly(variance seems constant).
plot(my_model, which =c(2))
- The Q-Q-plot most of the points are on line with little mix in the ends. Shows the error assumption. Seems good enough,
plot(my_model, which =c(5))
- Tells if there are influentical cases in the model. if there are cases on top right or bottom right, those would strongly influence the results.
3.1 & 3.2
library(GGally)
library(dplyr)
library(tidyr)
library(ggplot2)
alc <- read.table("data/alc.csv",header = TRUE)
colnames(alc)
## [1] "school" "sex" "age" "address" "famsize"
## [6] "Pstatus" "Medu" "Fedu" "Mjob" "Fjob"
## [11] "reason" "nursery" "internet" "guardian" "traveltime"
## [16] "studytime" "failures" "schoolsup" "famsup" "paid"
## [21] "activities" "higher" "romantic" "famrel" "freetime"
## [26] "goout" "Dalc" "Walc" "health" "absences"
## [31] "G1" "G2" "G3" "alc_use" "high_use"
The data is combination of two guestionaires made in portugal about school performance and alcohol usage. The two tables are combined to alc, data has 35 variables and 382 observations. Downloading the data and more information here: the tables are Student performansce data that can be studied or downloaded here: https://archive.ics.uci.edu/ml/datasets/Student+Performance . In addition: - The variables not used for joining the two data have been combined by averaging (including the grade variables) - ‘alc_use’ is the average of ‘Dalc’ and ‘Walc’ - ‘high_use’ is TRUE if ‘alc_use’ is higher than 2 and FALSE otherwise
3.3 The 4 hypothesis and interesting varibles I chose to explore are: absences, My guess is that more absences from school would lead to higher alcohol use because of lower grades and “rebellious” nature of the person. sex, hypothesis is that male will drink heavier than female. pstatus, hypothesis is that child of a divorced parents is more likely to be high user. G3(final grade) hypothesis is that high users are likely to get lower final score than low users. 3.4
gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar()
## Warning: attributes are not identical across measure variables;
## they will be dropped
alc %>% group_by(high_use, absences) %>% summarise(count = n())
## # A tibble: 42 x 3
## # Groups: high_use [?]
## high_use absences count
## <lgl> <int> <int>
## 1 FALSE 0 43
## 2 FALSE 1 29
## 3 FALSE 2 33
## 4 FALSE 3 28
## 5 FALSE 4 19
## 6 FALSE 5 11
## 7 FALSE 6 13
## 8 FALSE 7 5
## 9 FALSE 8 9
## 10 FALSE 9 4
## # ... with 32 more rows
alc %>% group_by(high_use, sex) %>% summarise(count = n())
## # A tibble: 4 x 3
## # Groups: high_use [?]
## high_use sex count
## <lgl> <fct> <int>
## 1 FALSE F 129
## 2 FALSE M 79
## 3 TRUE F 69
## 4 TRUE M 105
alc %>% group_by( Pstatus, high_use) %>% summarise(count = n())
## # A tibble: 4 x 3
## # Groups: Pstatus [?]
## Pstatus high_use count
## <fct> <lgl> <int>
## 1 A FALSE 24
## 2 A TRUE 14
## 3 T FALSE 184
## 4 T TRUE 160
alc %>% group_by(G3, high_use) %>% summarise(count = n())
## # A tibble: 32 x 3
## # Groups: G3 [?]
## G3 high_use count
## <int> <lgl> <int>
## 1 0 TRUE 2
## 2 2 TRUE 1
## 3 3 FALSE 1
## 4 4 FALSE 2
## 5 4 TRUE 5
## 6 5 FALSE 4
## 7 5 TRUE 2
## 8 6 FALSE 13
## 9 6 TRUE 9
## 10 7 FALSE 2
## # ... with 22 more rows
g1 <- ggplot(alc, aes(x = high_use, y = absences, col=sex))
g1 + geom_boxplot() + ggtitle("Student absences by alcohol consumption and sex")
g2 <- ggplot(alc, aes(x = high_use, y = G3, col=sex))
g2 + geom_boxplot()
m <- glm(high_use ~ absences + sex + Pstatus + G3, data = alc, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ absences + sex + Pstatus + G3, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.1325 -1.0311 -0.7191 1.0860 1.8230
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.53893 0.57856 -0.932 0.351590
## absences 0.07836 0.02306 3.399 0.000677 ***
## sexM 0.98733 0.21860 4.517 6.28e-06 ***
## PstatusT 0.51433 0.38235 1.345 0.178563
## G3 -0.08223 0.03368 -2.442 0.014622 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 526.53 on 381 degrees of freedom
## Residual deviance: 484.31 on 377 degrees of freedom
## AIC: 494.31
##
## Number of Fisher Scoring iterations: 4
coef(m)
## (Intercept) absences sexM PstatusT G3
## -0.53893271 0.07836256 0.98733119 0.51433491 -0.08223235
confint(m)
## Waiting for profiling to be done...
## 2.5 % 97.5 %
## (Intercept) -1.69202386 0.58461228
## absences 0.03553022 0.12614260
## sexM 0.56259330 1.42048666
## PstatusT -0.21859094 1.29130813
## G3 -0.14928605 -0.01692502
OR <- coef(m) %>% exp
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.5833705 0.1841465 1.7942952
## absences 1.0815147 1.0361690 1.1344439
## sexM 2.6840617 1.7552184 4.1391343
## PstatusT 1.6725257 0.8036504 3.6375418
## G3 0.9210579 0.8613227 0.9832174
abs <- ggplot(alc, aes(x = G3, fill = high_use)) +
geom_bar(position="fill")
abs
vars <- c("high_use","G3","absences","sex")
ggpairs(alc, columns = vars, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist")))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
- Boxplot show that for males high use is more related to g3 point, for female highuse doesnt really effect.
-There are 198 females and 184 male on the data set. propability for a female to be high user is 0.35 and 0.57 for male, so hypothesis was right. From cbind(OR, CI) we can see that odds for men high use are 2.7 times higher then for female.
-Pstatus worked differently then expected: in 38 situations parents lived apart and there´s 0.37 propability that student is high user. In situation where families lived together (364), 160 students reported high use, which is propability of 0.44, which is significantly higher. It has to be noted that there was so few famielies living apart that this is not definitive.
2.5 Pstatus is not significant so it will be dropped.
m <- glm(high_use ~ absences + sex + Pstatus + G3, data = alc, family = "binomial")
m <- glm(high_use ~ absences + sex + G3, data = alc, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ absences + sex + G3, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.2624 -1.0324 -0.7392 1.0978 1.8355
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.01459 0.42492 -0.034 0.9726
## absences 0.07455 0.02285 3.263 0.0011 **
## sexM 0.99179 0.21822 4.545 5.5e-06 ***
## G3 -0.08616 0.03350 -2.572 0.0101 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 526.53 on 381 degrees of freedom
## Residual deviance: 486.18 on 378 degrees of freedom
## AIC: 494.18
##
## Number of Fisher Scoring iterations: 4
coef(m)
## (Intercept) absences sexM G3
## -0.01459384 0.07455392 0.99179380 -0.08615843
confint(m)
## Waiting for profiling to be done...
## 2.5 % 97.5 %
## (Intercept) -0.84873690 0.82171416
## absences 0.03207927 0.12182000
## sexM 0.56786579 1.42426036
## G3 -0.15289901 -0.02123354
OR <- coef(m) %>% exp
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.9855121 0.4279551 2.2743952
## absences 1.0774034 1.0325994 1.1295508
## sexM 2.6960663 1.7644972 4.1547837
## G3 0.9174489 0.8582164 0.9789903
Pstatus was dropped since it was not significant. in the new model:
-Each point in absences raises the odds for 1.08. for 95% of the students one absence point raises high use risk between 1.03 & 1.13.
In sex its 2.7 times more likely for male to be high user than female. for 95% of the students the coefficients have an effect of 1.76-4.15
Each point in G3 decreases the risk for high use for 1-0.92. for 95% of the students the one point decreases between 0.86 and 0.98.
3.6
m <- glm(high_use ~ absences + Pstatus + sex + G3, data = alc, family = "binomial")
probabilities <- predict(m, type = "response")
alc <- mutate(alc, probability = probabilities)
alc <- mutate(alc, prediction = alc$probability>0.5)
select(alc, G3, absences, sex, high_use, probability, prediction) %>% tail(10)
## G3 absences sex high_use probability prediction
## 373 0 0 M TRUE 0.7236687 TRUE
## 374 2 7 M TRUE 0.7936071 TRUE
## 375 12 1 F TRUE 0.2823117 FALSE
## 376 8 6 F TRUE 0.4471281 FALSE
## 377 5 2 F FALSE 0.4306905 FALSE
## 378 12 2 F FALSE 0.2984561 FALSE
## 379 4 2 F TRUE 0.4509577 FALSE
## 380 4 3 F FALSE 0.4704247 FALSE
## 381 13 4 M TRUE 0.5516064 TRUE
## 382 10 2 M TRUE 0.5737420 TRUE
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE TRUE
## FALSE 151 57
## TRUE 79 95
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.3952880 0.1492147 0.5445026
## TRUE 0.2068063 0.2486911 0.4554974
## Sum 0.6020942 0.3979058 1.0000000
g <- ggplot(alc, aes(x = probability, y = high_use, col=prediction))
g + geom_point()
prediction says 0.60 for false, 0.40 for true. high_use is 0.54 for false and 46 for true. I will add failures to model to see what happens
m <- glm(high_use ~ absences + failures + sex + G3, data = alc, family = "binomial")
probabilities <- predict(m, type = "response")
alc <- mutate(alc, probability = probabilities)
alc <- mutate(alc, prediction = alc$probability>0.5)
select(alc, G3, absences, sex, high_use, probability, prediction) %>% tail(10)
## G3 absences sex high_use probability prediction
## 373 0 0 M TRUE 0.7322418 TRUE
## 374 2 7 M TRUE 0.8001864 TRUE
## 375 12 1 F TRUE 0.2669667 FALSE
## 376 8 6 F TRUE 0.4053126 FALSE
## 377 5 2 F FALSE 0.4649528 FALSE
## 378 12 2 F FALSE 0.2815204 FALSE
## 379 4 2 F TRUE 0.5657591 TRUE
## 380 4 3 F FALSE 0.4153810 FALSE
## 381 13 4 M TRUE 0.5276033 TRUE
## 382 10 2 M TRUE 0.5399197 TRUE
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE TRUE
## FALSE 158 50
## TRUE 80 94
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.4136126 0.1308901 0.5445026
## TRUE 0.2094241 0.2460733 0.4554974
## Sum 0.6230366 0.3769634 1.0000000
prediction false 0.62, true 0.38, high_use is the same 0.54 for false and 46 for true. so this model is worse then my initial.
define a loss function (mean prediction error)/proportion of inaccurately classified individuals (= the training error):
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)
}
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.3403141
The training error is 0.34, so it´s worse then the one in dataCamp exercises.
Bonus:
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.3403141
library(boot)
cv <- cv.glm(data = alc, cost = loss_func, glmfit = m, K = 10)
cv$delta[1]
## [1] 0.3560209
Chapter 4 - Clustering and classification Analysis 4.1.
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
library(dplyr)
library(GGally)
library(ggplot2)
library(tidyverse)
## -- Attaching packages --------------- tidyverse 1.2.1 --
## v tibble 1.4.2 v purrr 0.2.5
## v readr 1.3.1 v stringr 1.3.1
## v tibble 1.4.2 v forcats 0.3.0
## -- Conflicts ------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## x MASS::select() masks dplyr::select()
library(corrplot)
## corrplot 0.84 loaded
bhv <- Boston
str(bhv)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(bhv)
## [1] 506 14
The data is about housing values in suburbs of Boston and table has 14 variables and 506 observations. THe variables: < code >crim per capita crime rate by town. < code >zn proportion of residential land zoned for lots over 25,000 sq.ft. < code >indus proportion of non-retail business acres per town. < code >chas Charles River dummy variable (= 1 if tract bounds river; 0 otherwise). < code >nox nitrogen oxides concentration (parts per 10 million). < code >rm average number of rooms per dwelling. < code >age proportion of owner-occupied units built prior to 1940. < code >dis weighted mean of distances to five Boston employment centres. < code >rad index of accessibility to radial highways. < code >tax full-value property-tax rate per $10,000. < code >ptratio pupil-teacher ratio by town. < code >black 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town. < code >lstat lower status of the population (percent). < code >medv median value of owner-occupied homes in $1000s.
Lets change the variable names to more understandable ones.
new_names <- c("crime_rate","proposion_residental_land", "proportion_industrial", "river_bound", "Nitrogen_concentration", "rooms_per_house", "proportion_old_houses","distance_emplyment_center", "access_highways","tax_value", "pupil_teacher_ratio", "proportion_blacks", "lower_status", "house_values")
names(bhv) <-new_names
summary(bhv)
## crime_rate proposion_residental_land proportion_industrial
## Min. : 0.00632 Min. : 0.00 Min. : 0.46
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19
## Median : 0.25651 Median : 0.00 Median : 9.69
## Mean : 3.61352 Mean : 11.36 Mean :11.14
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10
## Max. :88.97620 Max. :100.00 Max. :27.74
## river_bound Nitrogen_concentration rooms_per_house
## Min. :0.00000 Min. :0.3850 Min. :3.561
## 1st Qu.:0.00000 1st Qu.:0.4490 1st Qu.:5.886
## Median :0.00000 Median :0.5380 Median :6.208
## Mean :0.06917 Mean :0.5547 Mean :6.285
## 3rd Qu.:0.00000 3rd Qu.:0.6240 3rd Qu.:6.623
## Max. :1.00000 Max. :0.8710 Max. :8.780
## proportion_old_houses distance_emplyment_center access_highways
## Min. : 2.90 Min. : 1.130 Min. : 1.000
## 1st Qu.: 45.02 1st Qu.: 2.100 1st Qu.: 4.000
## Median : 77.50 Median : 3.207 Median : 5.000
## Mean : 68.57 Mean : 3.795 Mean : 9.549
## 3rd Qu.: 94.08 3rd Qu.: 5.188 3rd Qu.:24.000
## Max. :100.00 Max. :12.127 Max. :24.000
## tax_value pupil_teacher_ratio proportion_blacks lower_status
## Min. :187.0 Min. :12.60 Min. : 0.32 Min. : 1.73
## 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38 1st Qu.: 6.95
## Median :330.0 Median :19.05 Median :391.44 Median :11.36
## Mean :408.2 Mean :18.46 Mean :356.67 Mean :12.65
## 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23 3rd Qu.:16.95
## Max. :711.0 Max. :22.00 Max. :396.90 Max. :37.97
## house_values
## Min. : 5.00
## 1st Qu.:17.02
## Median :21.20
## Mean :22.53
## 3rd Qu.:25.00
## Max. :50.00
ggpairs(bhv, columns = 1:14, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist")))
cor_matrix <- cor(Boston)
cor_matrix_rounded<-cor(bhv) %>% round(2)
corrplot(cor_matrix, method="number", type = "upper", cl.pos = "b", tl.pos = "a", tl.cex = 0.6)
-We dont know how the propotion of blacks is counted but from summary we can see that it´s heavily left skewed, minimum is 0.32, 1st qu 375.38 and Mean 356.67. This implies that there are few areas that have extremely small percentage of black people. -Crime rate seems to changing a lot, min is 0.00632, median 0.25651 and max 88.97620! So in some places 1000 people get caught/prosecuted from crimes 6.32 times, in the median area it´s 256.51 times and the maximum is 88976.20? So every citizen would make 89 crimes? I guess that can’t be right so im assuming this cant be directly read as amount of crimes. So according the data in some suburbs per capita there is 14000 times more crime then in others. In the correlation matrix we can see that the variables that correlate most are access to highways 0.6255 and tax value 0.5827. - Tax value correlates strongly with access to highways 0.9102 and propotion industrial 0.7207 -House values correlate with lower status -0.74 and 0.70 on rooms per house.
res1 <- cor.mtest(Boston, conf.level = .95)
corrplot(cor_matrix, p.mat = res1$p, method = "color", type = "upper",
sig.level = c(.001, .01, .05), pch.cex = .9,
insig = "label_sig", pch.col = "white", order = "AOE")
asd <- c(bhv$access_highways==24)
asb <- c(bhv$tax_value==666)
length(which(asb))
## [1] 132
length(which(asd))
## [1] 132
sum(asd,na.rm=T)
## [1] 132
4.2 Standardize the dataset and print out summaries of the scaled data. How did the variables change? Create a categorical variable of the crime rate in the Boston dataset (from the scaled crime rate). Use the quantiles as the break points in the categorical variable. Drop the old crime rate variable from the dataset. Divide the dataset to train and test sets, so that 80% of the data belongs to the train set.
bhv_scaled <- scale(bhv)
summary(bhv_scaled)
## crime_rate proposion_residental_land proportion_industrial
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## river_bound Nitrogen_concentration rooms_per_house
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681
## Median :-0.2723 Median :-0.1441 Median :-0.1084
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515
## proportion_old_houses distance_emplyment_center access_highways
## Min. :-2.3331 Min. :-1.2658 Min. :-0.9819
## 1st Qu.:-0.8366 1st Qu.:-0.8049 1st Qu.:-0.6373
## Median : 0.3171 Median :-0.2790 Median :-0.5225
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.9059 3rd Qu.: 0.6617 3rd Qu.: 1.6596
## Max. : 1.1164 Max. : 3.9566 Max. : 1.6596
## tax_value pupil_teacher_ratio proportion_blacks lower_status
## Min. :-1.3127 Min. :-2.7047 Min. :-3.9033 Min. :-1.5296
## 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049 1st Qu.:-0.7986
## Median :-0.4642 Median : 0.2746 Median : 0.3808 Median :-0.1811
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332 3rd Qu.: 0.6024
## Max. : 1.7964 Max. : 1.6372 Max. : 0.4406 Max. : 3.5453
## house_values
## Min. :-1.9063
## 1st Qu.:-0.5989
## Median :-0.1449
## Mean : 0.0000
## 3rd Qu.: 0.2683
## Max. : 2.9865
class(bhv_scaled)
## [1] "matrix"
bhv_scaled=as.data.frame(bhv_scaled)
-bhv_scaled was matrix so it´s turned into data frame. -Scaling substracts the mean of the column from each row, and then divides the difference with standard deviation. What we get is that all the variables are on similar scale. - Scaling is necessary for the later linear discriminant analysis, because it assumes the variables are normally distributed and each variable has same variance.
bins <- quantile(bhv_scaled$crime_rate)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
labels <- c("low", "med_low", "med_high", "high")
crime_rate <- cut(bhv_scaled$crime_rate, breaks =bins, include.lowest = TRUE, label = labels)
table(crime_rate)
## crime_rate
## low med_low med_high high
## 127 126 126 127
bhv_scaled <- dplyr::select(bhv_scaled, -crime_rate)
bhv_scaled <- data.frame(crime_rate, bhv_scaled)
-Tells how many people are in which group. - dropped the old criminal rate as the first column. - Dividing the data to test and train data 20/80%.The training of the model is done with the train set and prediction on new data is done with the test set. This way you have true classes / labels for the test data, and you can calculate how well the model performed in prediction.
# number of rows in the Boston dataset
n <- nrow(bhv_scaled)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- bhv_scaled[ind,]
# create test set
test <- bhv_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime_rate)
4.5 LDA is used to predict classes for new data and to find variables that either discriminate or separate the classes best (DataCamp). The difference between classification and clustering is, that in classification the classes are known and the model is trained with the training set from the data, and it classifies new values into classes. Clustering, on the other hand, means that the classes are unknown, but the data is grouped based on the similarities of the observations. If the assumptions of discriminant analysis are met, it is more powerful than logistic regression, but the assumptions are rarely met.
lda.fit <- lda(crime_rate ~ ., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime_rate ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2549505 0.2623762 0.2376238 0.2450495
##
## Group means:
## proposion_residental_land proportion_industrial river_bound
## low 0.9243751 -0.9181336 -0.08120770
## med_low -0.1464479 -0.3248204 -0.04947434
## med_high -0.3693281 0.1269967 0.17879700
## high -0.4872402 1.0171737 -0.11325431
## Nitrogen_concentration rooms_per_house proportion_old_houses
## low -0.8703345 0.42542273 -0.9349099
## med_low -0.5623754 -0.13761547 -0.3306342
## med_high 0.3790163 0.06295064 0.3885627
## high 1.0471848 -0.40582477 0.8353801
## distance_emplyment_center access_highways tax_value
## low 0.8468688 -0.6953119 -0.7360556
## med_low 0.3566738 -0.5463205 -0.5138076
## med_high -0.3456994 -0.4124230 -0.3329365
## high -0.8552144 1.6375616 1.5136504
## pupil_teacher_ratio proportion_blacks lower_status house_values
## low -0.47275774 0.3796707 -0.77005156 0.538815604
## med_low -0.07227757 0.3171522 -0.14780941 0.001254014
## med_high -0.31289868 0.1489397 -0.02321386 0.158395186
## high 0.78011702 -0.6994031 0.97345222 -0.760942012
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## proposion_residental_land 0.10932901 0.729662349 -0.96499476
## proportion_industrial 0.06401755 -0.222146613 0.32655459
## river_bound -0.10439841 -0.062391947 -0.02213733
## Nitrogen_concentration 0.31468547 -0.731942362 -1.49646424
## rooms_per_house -0.07609511 -0.054536033 -0.08220952
## proportion_old_houses 0.27082590 -0.418570222 -0.07616714
## distance_emplyment_center -0.07230497 -0.273682705 0.12764118
## access_highways 3.12088574 0.981377194 0.03332585
## tax_value 0.01398197 -0.097602436 0.39639810
## pupil_teacher_ratio 0.10777971 0.047518287 -0.28960557
## proportion_blacks -0.10785873 -0.005323416 0.11653126
## lower_status 0.18571588 -0.040414327 0.44398468
## house_values 0.14520157 -0.273417072 -0.21463413
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9472 0.0382 0.0147
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime_rate)
# plot the lda results
plot(lda.fit, dimen = 2,col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 7)
# or like this: plot(lda.fit, dimen = 2,col = classes, pch = classes) + lda.arrows(lda.fit, myscale = 7)
4.6 Save the crime categories from the test set and then remove the categorical crime variable from the test dataset. Then predict the classes with the LDA model on the test data. Cross tabulate the results with the crime categories from the test set. Comment on the results.
Next phase is to fit the testing data to the LDA and predict the classes for the values. Since the correct values are stoder in the correct_classes variable, I will cross-tabulate the predicted values and the correct values to see whether the classifier classified the values correctly.
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 14 9 1 0
## med_low 7 9 4 0
## med_high 0 8 21 1
## high 0 0 0 28
table(correct = correct_classes)
## correct
## low med_low med_high high
## 24 20 30 28
table(predicted = lda.pred$class)
## predicted
## low med_low med_high high
## 21 26 26 29
-Model seems to predict crime rate reasonably well. - High rates are all correct. - Half of the actual med. highs are predicted as med.low. - From actual med. low half wornd, divded on low and med. high. - On actual low, model tends puts more than hald on med. low and one on med.high so it´s not effective on predicting low crime rates.
4.7 Reload and standardize Boston data set. Scale the variables to get comparable distances
data("Boston")
b_scaled <- scale(Boston)
names(b_scaled) <-new_names
b_scaled <- as.data.frame(b_scaled)
# euclidean distance matrix
dist_eu <- dist(b_scaled)
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(b_scaled, method = "manhattan")
# look at the summary of the distances
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
set.seed(123)
# determining the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(b_scaled, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')
# k-means clustering, 2 is the steepest corner so we pick 2 clusters.
km <-kmeans(b_scaled, centers = 2)
# plot the Boston dataset with clusters
pairs(b_scaled, col = km$cluster)
#Error in plot.new() : figure margins too large, give the command on console.
pairs(b_scaled[1:10], col = km$cluster)
- Data is spread into two clusters that are quite differerent from eachother. We can see from the graph what we earlier saw numerically from the datatable. In the upper row we have crime against the variables, and we can see that cluster #2 has higher crime rates in every aspect than cluster #1.
Bonus:
data(Boston)
b_scaled <- scale(Boston)
names(b_scaled) <-new_names
b_scaled <- as.data.frame(b_scaled)
km <- kmeans(b_scaled, centers = 3)
km
## K-means clustering with 3 clusters of sizes 152, 216, 138
##
## Cluster means:
## crim zn indus chas nox rm
## 1 0.8942488 -0.4872402 1.0913679 -0.01330932 1.1109351 -0.4609873
## 2 -0.3688324 -0.3935457 -0.1369208 0.07398993 -0.1662087 -0.1700456
## 3 -0.4076669 1.1526549 -0.9877755 -0.10115080 -0.9634859 0.7739125
## age dis rad tax ptratio black
## 1 0.7828949 -0.84882600 1.3656860 1.3895093 0.63256391 -0.7083974
## 2 0.1673019 -0.07766431 -0.5799077 -0.5409630 -0.04596655 0.2680397
## 3 -1.1241828 1.05650031 -0.5965522 -0.6837494 -0.62478941 0.3607235
## lstat medv
## 1 0.90799414 -0.69550394
## 2 -0.05818052 -0.04811607
## 3 -0.90904433 0.84137443
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 3 2 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 2 2 2 3 3 3 3 3 2 2 2 2 2 2 3 3 3 3
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 3 3 3 3 3 3 2 2 3 3 3 3 3 3 2 3 3 2
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 3 3 2 2 2 2 2 2 3 3 3 3 2 2 2 2 2 2
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 2 2 2 3 2 2 2 3 3 3 2 2 2 2 2 2 2 2
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 2 2 2 2 2 2 2 2 1 2 2 2 1 2 1 1 1 1
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 1 1 1 1 1 1 2 2 2 1 2 1 1 2 2 2 2 2
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 3
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 3 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 2 2 2 2 2 2 2 2 3 3 3 2 3 3 2 2 3 3
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 2 2 2 2 3 3 3 3 3 3 2 2 3 2 3 3 3 3
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 3 3 3 3 3 3 2 2 2 3 3 2 2 2 2 3 3 2
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 2 3 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 3 3 3 3 3 3 2 3 2 2 3 3 3 3 3 3 3 3
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 2 3 2 2 2 3 3 3 3 2 2 2 2 2 2 2 2 3
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 2 3 3 2 2 3 3 3 3 3 3 3 3 3 1 1 1 1
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
## 505 506
## 2 2
##
## Within cluster sum of squares by cluster:
## [1] 1552.2502 1362.4417 961.7037
## (between_SS / total_SS = 45.2 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
lda.fit <- lda(km$cluster~., data=b_scaled)
classes<-as.numeric(km$cluster)
plot(lda.fit, dimen = 2, col=classes)
lda.arrows(lda.fit, myscale = 4)
drawing the clusters and arrows. here we can see which variables are meaningful to which cluster.
Bonus #2
data("Boston")
b_scaled <- scale(Boston)
b_scaled <- as.data.frame(b_scaled)
set.seed(123) #Setting seed
bins <- quantile(b_scaled$crim)
# create a categorical variable 'crime'
crime <- cut(b_scaled$crim, breaks = bins, include.lowest = TRUE, label=c("low","med_low","med_high","high"))
# look at the table of the new factor crime
#table(crime)
# remove original crim from the dataset
b_scaled <- dplyr::select(b_scaled, -crim)
# add the new categorical value to scaled data
b_scaled <- data.frame(b_scaled, crime)
# number of rows in the Boston dataset
n <- nrow(b_scaled)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- b_scaled[ind,]
# create test set
test <- b_scaled[-ind,]
lda.fit <- lda(crime ~ ., data = train)
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
set.seed(123)
data("Boston")
boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
myset <- boston_scaled[ind,]
km <-kmeans(myset, centers = 2)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = km$cluster)